package com.bb.blog.security.service.wx;

import com.bb.blog.web.exception.ServerException;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

@RequiredArgsConstructor
public class WxAccessTokenService {
    private final RedisTemplate<Object,Object> redisTemplate;
    private final RestTemplate restTemplate;
    private final WxRequestFactory wxRequestFactory;
    private String key = WxAccessTokenService.class.toString();

    public String getAccessToken(){
        String token = (String) redisTemplate.opsForValue().get(key);
        if(token!= null ){
            return token;
        }
        // 发起请求
        RequestEntity requestEntity = wxRequestFactory.accessToken();
        ResponseEntity<WxAccessToken> resEntity = restTemplate.exchange(requestEntity,WxAccessToken.class);

        WxAccessToken wxAccessToken = resEntity.getBody();
        if(wxAccessToken == null ||wxAccessToken.getErrcode()!=null){
            throw new ServerException(500,"访问wx客户端出现异常");
        }
        redisTemplate.opsForValue().set(key,wxAccessToken.getAccess_token(),wxAccessToken.getExpires_in(), TimeUnit.SECONDS);
        return wxAccessToken.getAccess_token();
    }



}
